<template>
  <div class="container">
    <!--    <UnifyTitle/>-->

    <base-header
      ref="baseheader"
      @onSearch="onSearch"
      :tagList="tagList"
    ></base-header>

    <!-- 检索区 -->
    <div class="flex space-between">
      <div
        class="tree-list pl5 pt15 pr5 mr12 bgFFF bdradius4"
        style="width: 290px"
      >
        <div class="block">
          <org-structure @search="onTreeSearch"></org-structure>
        </div>
      </div>
      <div class="pl20 pr20 bgFFF bdradius4 btn-section" style="width: calc(100% - 300px)">
        <!-- 表头区 -->
        <div class="flex space-between mt10">
          <div class="flex flex-y-center">
            <button-menu
              @handleAdd="handleAdd"
              @batchDelete="batchDelete"
              @handleImport="importModal = true"
              @handleExport="daochu"
            ></button-menu>
          </div>
          <div class="flex flex-y-center">
            <RadioGroup
              v-model="criteria.auditStatusList"
              type="button"
              @on-change="handleStatus"
            >
              <Radio label="[]">全部</Radio>
              <Radio label="[0,1]">审核中</Radio>
              <Radio label="[2]">审核通过</Radio>
              <Radio label="[3]">审核驳回</Radio>
            </RadioGroup>
          </div>
        </div>
        <!-- 列表区 -->
        <BaseTable
          class="table"
          ref="table"
          :loading="tableLoading"
          v-model="criteria"
          :columns="columns"
          :data="tableData"
          :selection="true"
          @on-search="loadData"
          @selectionChange="selectionChange"
        >
        </BaseTable>
      </div>
    </div>

    <!--  查看抽屉  -->
    <base-drawers
      v-model="showViewDrawers"
      title="居民信息"
      :showButton="false"
      @input="cancelBt('showViewDrawers')"
    >
      <detail
        ref="detail"
        detail-request-name="addResidentDetail"
        log-request-name="addResidentOperatingLog"
        :columns-log="columnsLog"
      ></detail>
    </base-drawers>
    <!--  编辑抽屉  -->
    <base-drawers
      v-model="showDrawers"
      :title="modalTitle"
      @input="cancelBt('showDrawers')"
      :loading="drawerLoading"
      submitBtn="提交"
      @drawerSubmit="drawerSubmit"
    >
      <div>
        <Form ref="form" :rules="rules" :label-width="105" :model="form">
          <FormItem label="增员方式" v-if="addWayList.length">
            <RadioGroup v-model="addWay">
              <Radio v-for="item in addWayList" :key="item.value" :label="item.value">{{ item.label }}</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem prop="pickDate" label="增员时间">
            <DatePicker
              v-model="form.pickDate"
              type="year"
              clearable
              placeholder="请选择增员时间"
              format="yyyy"
              @on-change="handleDaterangeInput"
              :transfer="true"
              :editable="false"
              :disabled="true"
              style="width: 280px"
            ></DatePicker>
          </FormItem>
          <div v-if="addWay === '1'">
            <FormItem prop="name" label="居民姓名">
              <Input
                type="text"
                placeholder="请输入居民姓名"
                clearable
                maxlength="20"
                v-model="form.name"
                :disabled="formDisabled"
                style="width: 280px"
              /></FormItem>
            <FormItem prop="idCard" label="身份证号">
              <Input
                type="text"
                placeholder="请输入身份证号"
                maxlength="18"
                clearable
                v-model="form.idCard"
                :disabled="formDisabled"
                style="width: 280px"
              /></FormItem>
            <FormItem prop="phone" label="联系电话">
              <Input
                type="text"
                placeholder="请输入联系电话"
                clearable
                maxlength="11"
                v-model="form.phone"
                style="width: 280px"
              /></FormItem>
            <FormItem prop="address" label="户籍所在地">
              <Input
                type="text"
                placeholder="请输入户籍所在地"
                clearable
                maxlength="50"
                v-model="form.address"
                style="width: 280px"
              /></FormItem>
            <!--            <FormItem prop="tagIdList" label="标签">
              <Select
                v-model="form.tagIdList"
                multiple
                transfer
                style="width: 280px"
                placeholder="请选择标签"
              >
                <OptionGroup
                  :label="item.tagName"
                  v-for="item in tagList"
                  :key="item.id"
                >
                  <Option
                    v-for="itemC in item.children"
                    :value="itemC.id"
                    :key="itemC.id"
                    >{{ itemC.tagName }}</Option
                  >
                </OptionGroup>
              </Select>
            </FormItem>-->
          </div>
          <FormItem prop="year" label="上传表格" v-else>
            <Button
              type="primary"
              class="flex flex-y-center flex-x-center"
              style="height: 28px"
              @click="importModal = true"
            >导入人员
            </Button
            >
          </FormItem>
          <FormItem prop="remark" label="备注">
            <Input
              type="textarea"
              placeholder="请输入备注内容"
              :rows="6"
              v-model="form.remark"
              style="width: 280px"
            /></FormItem>
        </Form>
      </div>
    </base-drawers>

    <!--  审核  -->
    <base-modal
      ref="auditModal"
      :loading="modalBtnLoading"
      :quxiao="quxiao"
      :buttonif="buttonif"
      v-model="auditModal"
      @closeM="cancelBt('auditModal')"
      @closeBt="rejectBtn"
      @submitBt="okSave"
      titleText="增员审核"
      cancelText="驳回"
      okText="通过"
      :styles="{ width: '600px' }"
    >
      <div style="padding: 14px 64px">
        <div class="mb20 color333 line16">
          <span class="tr inlineblock" style="width: 180px">居民姓名</span>
          <span class="ml10 inlineblock" style="width: calc(100% - 190px);vertical-align: top;">{{ auditDetail.name }}</span>
        </div>
        <div class="mb20 color333 line16">
          <span class="tr inlineblock" style="width: 180px">户籍所在地</span>
          <span class="ml10 inlineblock" style="width: calc(100% - 190px);vertical-align: top;">{{ auditDetail.address }}</span>
        </div>
        <div class="mb20 color333 line16">
          <span class="tr inlineblock" style="width: 180px">身份证号</span>
          <span class="ml10">{{ auditDetail.idCard }}</span>
        </div>
        <div class="mb20 color333 line16">
          <span class="tr inlineblock" style="width: 180px">联系电话</span>
          <span class="ml10">{{ auditDetail.phone }}</span>
        </div>
        <div class="mb20 color333 line16">
          <span class="tr inlineblock" style="width: 180px">增员年份</span>
          <span class="ml10">{{ auditDetail.year }}</span>
        </div>
        <div class="mb20 color333 line16">
          <span class="tr inlineblock" style="width: 180px">提交人</span>
          <span class="ml10">{{ auditDetail.createName }}</span>
        </div>
        <div class="mb20 color333 line16">
          <span class="tr inlineblock" style="width: 180px">提交时间</span>
          <span class="ml10">{{ auditDetail.createDate }}</span>
        </div>
        <div class="mb20 color333 line16">
          <span class="tr inlineblock" style="width: 180px">备注</span>
          <span class="ml10 inlineblock" style="width: calc(100% - 190px);vertical-align: top;">{{ auditDetail.remark }}</span>
        </div>
      </div>
    </base-modal>

    <!-- 导入数据弹窗 -->
    <import-modal
      :importModal="importModal"
      titleText="导入人员"
      :requestUrl="'/data/import/upload-excel/resident-add/' + form.year"
      downloadTempUrl="/t/%E5%A2%9E%E5%91%98%E5%B1%85%E6%B0%91%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx"
      :importType="2"
      @cancel="importModal = false"
      @success="chenggdaoru"
    />
    <!-- 审核驳回弹框 -->
    <base-modal
      ref="shenhbh"
      :loading="shbhloading"
      :quxiao="shbhqx"
      v-model="shbhmodel"
      @closeM="shbhclos"
      @closeBt="shbhcobt"
      @submitBt="shbhsub"
      titleText="驳回原因"
      cancelText="取消"
      okText="提交"
      :styles="{ width: '600px', top: '170px' }"
    >
      <div>
        <Form ref="formInline" :model="formInline" :rules="ruleInline" inline>
          <FormItem
            prop="remark"
            label="驳回原因"
            style="
              display: flex;
              margin: 0 auto;
              justify-content: center;
              padding: 25px 0;
            "
          >
            <Input
              v-model="formInline.remark"
              type="textarea"
              :rows="5"
              placeholder="请输入驳回原因"
              :maxlength="150"
              style="width: 280px"
            />
          </FormItem>
        </Form>
      </div>
    </base-modal>
  </div>
</template>

<script>
import FromOne from "@/libs/jss/FormValidation";
import BaseHeader from "./components/base-header";
import BaseDrawers from "_c/base-drawers/base-drawers";
import BaseModal from "_c/base-modal";
import labelInfo from "_c/labelInfo/labelInfo";
import Detail from "./components/detail";
import orgStructure from "_c/orgStructure/orgStructure";
import importModal from "_c/importModal/importModal";

export default {
  components: {
    BaseHeader,
    BaseDrawers,
    BaseModal,
    labelInfo,
    Detail,
    orgStructure,
    importModal,
  },
  data() {
    return {
      formInline: {
        remark: "",
      },
      ruleInline: {
        remark: [
          {required: true, message: "请输入驳回原因", trigger: "blur"},
        ],
      },
      shbhmodel: false,
      shbhloading: false,
      shbhqx: false,
      buttonif: true,
      showAuditStatusList: [],
      tableLoading: false,
      tableData: [], // 列表绑定数据
      tagList: [],
      /**
       * 查询条件
       */
      criteria: {
        total: 0,
        page: {
          current: 1,
          size: 10,
        },
        auditStatusList: "[]",
      },
      /**
       * 表格字段
       */
      columns: [
        {
          fixed: "left",
          title: "姓名",
          key: "name",
          width: 150,
          align: "left",
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
        },
        {
          title: "增员年份",
          key: "year",
          align: "left",
          minWidth: 100,
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
        },
        {
          title: "身份证号",
          key: "idCard",
          align: "left",
          width: 190,
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
          render: (h, params) => {
            return h(
              "span",
              {style: {textAlign: "left"}},
              this.commonFn(params.row.idCard, 6, 4)
            );
          },
        },
        {
          title: "联系电话",
          key: "phone",
          align: "left",
          width: 170,
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
        },
        {
          title: "户籍所在地",
          key: "address",
          align: "left",
          width: 180,
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
        },
        {
          title: "来源",
          key: "source",
          align: "left",
          width: 100,
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
          //  1-主动添加 2-批量导入3-缴费补充
          render: (h, params) => {
            let source = "";
            if (params.row.source == 1) {
              source = "主动添加";
            } else if (params.row.source == 2) {
              source = "批量导入";
            } else if (params.row.source == 3) {
              source = "缴费补充";
            }
            return h("span", {style: {textAlign: "left"}}, source);
          },
        },
        /*{
          title: "标签",
          key: "tagList",
          align: "left",
          minWidth: 400,
          render: (h, params) => {
            var arr = [];
            if (params.row.tagList) {
              for (let i = 0; i < params.row.tagList.length; i++) {
                arr.push(params.row.tagList[i].tagName);
              }
            }
            return (
              <div>
                <labelInfo labelInfo={arr}></labelInfo>
              </div>
            );
          },
        },*/
        {
          title: "审核状态",
          key: "auditStatus",
          align: "left",
          minWidth: 220,
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
          render: (h, params) => {
            // 0 未审核 1乡级审核通过 2 审核通过 3驳回
            let auditStatus = "";
            if (params.row.auditStatus == 0) {
              auditStatus = "创建成功，待乡级审核。";
            } else if(params.row.auditStatus == 1){
              auditStatus = "乡级审核成功，待县级审核。";
            } else if (params.row.auditStatus == 2) {
              auditStatus = "审核通过";
            } else if (params.row.auditStatus == 3) {
              auditStatus = "审核驳回";
            }
            return h("span", {style: {textAlign: "left"}}, auditStatus);
          },
        },
        {
          title: "备注",
          key: "remark",
          align: "left",
          minWidth: 160,
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
        },
      ],

      batchSelectionData: [],
      modalTitle: "",
      //查看
      showViewDrawers: false,
      columnsLog: [
        {
          title: "操作人",
          key: "auditName",
          align: "left",
          width: 140,
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
        },
        {
          title: "内容",
          key: "auditDesc",
          align: "left",
          minWidth: 200,
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
        },
        {
          title: "操作时间",
          key: "createDate",
          align: "left",
          width: 175,
          ellipsis: true,
          tooltip: true,
          tooltipTheme: "light",
        },
      ],
      // 编辑
      showDrawers: false,
      drawerLoading: false,
      form: {},
      formDisabled: false,  // 身份证号、姓名 只读
      form1: {},
      addWay: "1",
      addWayList: [],
      rules: {
        pickDate: [
          {
            type: "string",
            required: true,
            message: "请选择增员时间",
            trigger: "change",
          },
        ],
        name: [
          {
            required: true,
            message: "请输入居民姓名",
            trigger: "blur",
          },
        ],
        phone: [{
          required: true,
          message: "请输入正确的电话",
          trigger: "blur",
          validator: FromOne.FormValidate.FormOne().phone,
        }],
        idCard: [
          {
            required: true,
            message: "请输入正确的身份证号",
            trigger: "blur",
            validator: FromOne.FormValidate.FormOne().id,
          },
        ],
        /*remark: [
          {
            required: true,
            message: "请输入备注内容",
            trigger: "blur",
          },
        ],*/
      },

      // 审核
      auditModal: false,
      modalBtnLoading: false,
      quxiao: false,
      auditDetail: {},

      importModal: false,
    };
  },
  computed: {},
  watch: {},
  created() {
    let buttonMenu = this.buttonMenu(this.$route.name);
    this.columns.push(this.columnMenu(buttonMenu.buttonRight, this, 170));
    // this.getTagList();
    //  增员年份 默认选中明年
    let date = new Date().getFullYear() + 1;
    this.form.pickDate = date.toString();
    this.form.year = date.toString();
    this.ifshenhe()
  },
  methods: {
    // 导出
    daochu(){
      let data = {
        ...this.criteria,
      };
      data.auditStatusList = JSON.parse(data.auditStatusList);
      this.APIS.addResidentExport(data).then((res) => {
        const name = '增员列表'
        const blob = new Blob([res], { type: "application/vnd.ms-excel" });
        var url = window.URL.createObjectURL(blob);
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = url;
        link.setAttribute("download", name);
        document.body.appendChild(link);
        link.click();
      })
    },
    // 审核驳回弹框确认按钮
    shbhsub() {
      this.$refs.formInline.validate((valid) => {
        if (valid) {
          this.shbhloading = true;
          this.APIS.pejectadd({
            id: this.auditDetail.id,
            remark: this.formInline.remark,
          }).then((res) => {
            this.shbhloading = false;
            if (res.code == 20000) {
              this.shbhmodel = false;
              this.formInline.remark = "";
              this.$Message.success('驳回成功');
              this.auditModal = false;
              this.loadData();
            } else {
              this.$Message.warning(res.message);
            }
          });
        } else {

        }
      });
    },
    // 审核驳回弹框取消按钮
    shbhcobt() {
      this.shbhmodel = false;
      this.formInline.remark = "";
    },
    // 审核驳回弹框关闭回调
    shbhclos() {
      this.shbhmodel = false;
      this.formInline.remark = "";
    },
    onTreeSearch(data) {
      this.criteria.deptIdSet = data.deptIdSet.length
        ? data.deptIdSet
        : [data.qywechatDeptId];
      this.criteria.page.current = 1;
      this.criteria.total = 0;
      this.loadData();
    },
    onSearch(data) {
      this.criteria = {
        ...data,
        auditStatusList: this.criteria.auditStatusList,
        deptIdSet: this.criteria.deptIdSet,
      };
      this.loadData();
    },
    // 获取标签列表
    /*getTagList() {
      this.APIS.tagList().then((res) => {
        if (res.code == 20000) {
          this.tagList = this.handleTree(res.data);
        } else {
          this.$Message.error(res.message);
        }
      });
    },*/
    handleStatus() {
      this.criteria.page.current = 1;
      this.criteria.page.total = 0;
      this.loadData();
    },
    // 初始化获取列表数据
    loadData() {
      this.tableLoading = true;
      let data = {
        ...this.criteria,
      };
      data.auditStatusList = JSON.parse(data.auditStatusList);
      this.APIS.addResidentList(data)
        .then((res) => {
          this.tableLoading = false;
          if (res.code == 20000) {
            if (res.data.total) {
              res.data.records.map((item) => {
                if (this.showAuditStatusList.indexOf(item.auditStatus) == -1) {
                  item.hide = true;
                }
                // 审核驳回编辑信息
                if (item.auditStatus != 3) {
                  item.editHide = true;
                }
                return item;
              });
            }
            this.criteria.total = res.data.total;
            this.tableData = res.data.records;

            // 新增
            if (this.$route.params.add) {
              // 有增员权限时打开增员弹窗
              let buttonMenu = this.buttonMenu(this.$route.name);
              if (buttonMenu.buttonTop.find(item => item.name.indexOf('xinzeng') != -1 || item.name.indexOf('xinjian') != -1 || item.name.indexOf('tianjia') != -1 || item.name.indexOf('zengyuan') != -1)) {
                this.handleAdd();
                delete this.$route.params.add;
              }
            }
          } else {
            this.$Message.error(res.message);
          }
        })
        .catch((err) => {
          this.tableLoading = false;
        });
    },
    //  批量删除
    batchDelete() {
      if (this.batchSelectionData.length > 0) {
      } else {
        this.$Message.warning("请先勾选数据");
      }
    },
    handleAdd() {
      this.modalTitle = "增员";
      this.drawerLoading = false;
      if (localStorage.getItem("import") === "true") {
        this.addWayList = [{
          value: "1",
          label: "手动增员"
        }, {
          value: "2",
          label: "导入数据"
        }]
      }
      // this.formDisabled = false;
      this.showDrawers = true;
    },
    // 查看
    handleView(params) {
      this.showViewDrawers = true;
      this.$refs.detail.getDetail(params);
    },
    // 编辑
    handleEdit(params) {
      // 详情
      this.APIS.addResidentDetail({id: params.id}).then((res) => {
        if (res.code == 20000) {
          if (res.data.year) {
            // res.data.pickDate = new Date(Date.parse(res.data.year));
            res.data.pickDate = res.data.year.toString();
          } else {
            let date = new Date().getFullYear() + 1;
            // res.data.pickDate = new Date(Date.parse(date));
            res.data.pickDate = date.toString();
            res.data.year = date.toString();
          }
          this.form1 = JSON.parse(JSON.stringify(res.data));
          this.form = JSON.parse(JSON.stringify(res.data));
          this.modalTitle = "增员";
          this.drawerLoading = false;
          // this.formDisabled = true;
          this.showDrawers = true;
        } else {
          this.$Message.error(res.message);
        }
      });
    },
    // 增员时间
    handleDaterangeInput(data) {
      this.form.year = data;
    },
    // 编辑弹框确定
    drawerSubmit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.drawerLoading = true;
          let datas = JSON.parse(JSON.stringify(this.form));
          delete datas.pickDate;
          if (datas.id == null || datas.id == undefined || datas.id === "") {
            this.APIS.addResidentAdd(datas).then((res) => {
              this.drawerLoading = false;
              if (res.code == 20000) {
                this.$Message.success("新建成功");
                this.cancelBt("showDrawers");
                this.loadData();
              } else {
                this.$Message.error(res.message);
              }
            });
          } else {
            let data = {
              id: datas.id,
              year:datas.year,
            };
            for (let i in datas) {
              if (datas[i] !== this.form1[i]) {
                data[i] = datas[i];
              }
            }
            this.APIS.addResidentUpdate(data).then((res) => {
              this.drawerLoading = false;
              if (res.code == 20000) {
                this.$Message.success("提交成功");
                this.cancelBt('showDrawers');
                this.loadData();
              } else {
                this.$Message.error(res.message)
              }
            });
          }
        }
      });
    },

    // 审核
    handleAudit(params) {
      this.auditDetail = {};
      // 详情
      this.APIS.addResidentDetail({id: params.id}).then((res) => {
        if (res.code == 20000) {
          this.auditDetail = res.data;
          // this.ifshenhe();
          this.modalBtnLoading = false;
          this.quxiao = false;
          this.auditModal = true;
        } else {
          this.$Message.error(res.message);
        }
      });
    },
    // 判断能不能审核
    ifshenhe() {
      this.APIS.auditstatus({definitionId: "1"}).then((res) => {
        if (res.code == 20000) {
          this.showAuditStatusList = res.data;
          /*if (
            this.auditDetail.auditStatus == 0 ||
            this.auditDetail.auditStatus == 1
          ) {
            if(res.data.indexOf(this.auditDetail.auditStatus) == -1){
              this.buttonif = false;
            }else{
              this.buttonif = true;
            }
          } else if (this.auditDetail.auditStatus == 2) {
            this.buttonif = false;
          } else if (this.auditDetail.auditStatus == 3) {
            this.buttonif = false;
          }*/
        } else {
          this.$Message.warning(res.message);
        }
      });
    },
    // 审核驳回
    rejectBtn() {
      this.shbhmodel = true;
    },
    // 审核通过
    okSave() {
      this.modalBtnLoading = true;
      this.APIS.passadd({id: this.auditDetail.id, remark: ""}).then((res) => {
        this.modalBtnLoading = false;
        if (res.code == 20000) {
          this.$Message.success("审批成功");
          this.auditModal = false;
          this.loadData();
        } else {
          this.$Message.warning(res.message);
        }
      });
    },
    // 关闭抽屉
    cancelBt(drawerName) {
      // this.buttonif = false
      this[drawerName] = false;
      this.form = {
        pickDate: this.form.pickDate,
        year: this.form.year
      };
      this.addWayList = [];
      this.addWay = "1";
      this.$refs.form.resetFields();
    },

    selectionChange(data) {
      this.batchSelectionData = data;
    },
    chenggdaoru() {
      this.importModal = false;
      this.criteria.page.current = 1;
      this.criteria.page.total = 0;
      this.loadData();
    },
  },
};
</script>


<style lang="less" scoped>
@import "../setUp/contactsManagement/index";

.table {
  /deep/ .ivu-card-body {
    padding: 0 !important;
  }
}

/*/deep/ .ivu-input[disabled], /deep/ fieldset[disabled] .ivu-input {
  background-color: transparent;
}*/
</style>
